const { h, v } = require('./base');
const { clone, printTable, printLine, init, isWin } = require('./util')
const logic2 = require('./log2')

const showStep = 38;
const isDebug = false;

let res = [], step = 0, lastStep;

const getBase = (isHorizon, index, length) => {
    let _res = [];

    if (isHorizon) {
        for (let i = 0; i < length; i++) {
            _res.push(res[i][index]);
        }
    } else {
        _res = clone(res[index])
    }

    return _res;
};

const setResult = (isHorizon, index, data, length) => {
    if (isHorizon) {
        for (let i = 0; i < length; i++) {
            res[i][index] = data[i];
        }
    } else {
        for (let i = 0; i < res[index].length; i++) {
            res[index][i] = data[i];
        }
    }
};

const _fillOnce = (isHorizon, fn) => {
    let arr = isHorizon ? h : v, opLength = (isHorizon ? v : h).length;

    for (let index = 0; index < arr.length; index++) {
        if (isWin(res)) {
            console.log('Already win!');
            break;
        }
        let base = getBase(isHorizon, index, opLength);

        if (isDebug) {
            console.log(`[Step ${step}] : ${isHorizon ? "Column" : "Row"} ${index + 1}.`);
            console.log(printLine(base), ' => ', arr[index], '\n');
        }

        let temp = fn(clone(base), clone(arr[index]), step);

        setResult(isHorizon, index, temp, opLength);

        if (JSON.stringify(temp) !== JSON.stringify(base)) {

            step++;
            // logic.setIsShow(step === showStep);
            console.log(`[Step ${step}] : ${isHorizon ? "Column" : "Row"} ${index + 1}.`);
            console.log(printLine(base), ' => ', printLine(temp), ' | ', arr[index], '\n');
            console.log(printTable(res, h, v));
        }
    }
}

const main = () => {
    res = init();

    while (!isWin(res) && lastStep !== step) {
        lastStep = step;
        _fillOnce(true, logic2.enumerate)
        _fillOnce(false, logic2.enumerate)
    }

    if (lastStep === step) {
        console.log('\n\nFail to solve this!')
    }
}

main()